package com.reflect.util;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created with IntelliJ IDEA.
 * Description:
 *
 * @author lzy
 * @create 2019-03-29 下午2:32
 */
public class ReflectionUtils {
    /**
     * 通过反射,获取Class定义中声明的父类的泛型参数的类型
     * 如果没有找到,返回Ojbcet.class
     *
     * @param clazz
     * @param index
     * @return
     */
    public static Class getClassGenericType(final Class clazz, final int index) {
        Type genType = clazz.getGenericSuperclass();
        if (!(genType instanceof ParameterizedType)) {
            System.out.println(clazz.getSimpleName() + "'s superclass not parameterizedType");
            return Object.class;
        }

        Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
        if ((index >= params.length) || index < 0) {
            System.out.println("Index:" + index + ", Size of " + clazz.getSimpleName() + "'s parameterized type:" + params.length);
            return Object.class;
        }

        if (!(params[index] instanceof Class)) {
            System.out.println(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
            return Object.class;
        }

        return (Class) params[index];
    }

    /**
     * 获取唯一的泛型类型
     *
     * @param clazz
     * @return
     */
    public static Class getOnlyOneClassGenericType(Class clazz) {
        return getClassGenericType(clazz, 0);
    }
}
